<?php
namespace app\hotel\model;

use think\Model;
use think\Db;
use think\Session;
use think\Request;
use app\common\model\UserModel as um;
use app\common\model\OrderCancelModel as ocm; 
use app\common\model\OrderRefund as orf;
use app\common\model\LogOrderModel as lo;
use app\api\model\OrderRefund as ore;
class Order extends Model
{

    static function orderList($field,$where,$startrow = 0, $pageSize = 0, $isCount = false){

        $hotel_id = Session::get('hotel_id');

        $query = Db::name('hotel_order')->alias('t1')->where('hotel_id',$hotel_id)->where($where);

        if ($isCount){

            return $query->count();

        }

        if ($pageSize){

            return $query
                ->order('order_id desc')
                ->limit($startrow,$pageSize)
                ->select();

        }

        return $query->select();

    }

    static function shopOrdersByPage($orderStatus, $isCount = false)
    { 
         $where = array(); 
         $get = Request::instance()->get();  
          $hotel_id = Session::get('hotel_id');
          $where = ['hotel_id'=>$hotel_id,'is_del'=>0];
            if (isset($get['order_sn']) && $get['order_sn'] != '' ){
                $where['o.order_sn'] =  array('like', '%' . $get['order_sn'] . '%');
            } 
             if (isset($get['linkman']) && $get['linkman'] != '' ){
                $where['o.linkman'] =  array('like', '%' . $get['linkman'] . '%');
            }
             if (isset($get['tel']) && $get['tel'] != '' ){
                $where['o.tel'] =  array('like', '%' . $get['tel'] . '%');
            }
            if (isset($get['order_status']) && $get['order_status'] != ''){
                $where['order_status'] = $get['order_status'];
            }
            if (isset($get['cancel_code']) && $get['cancel_code'] != ''){
                $where['cancel_code'] = 'hotel_cancle_code_'.$get['cancel_code'];
            }   
           if (isset($get['selectdate']) && $get['selectdate'] != ''){
                $created_at=explode(' ~ ', $get['selectdate']); 
                if (isset($created_at) && is_array($created_at)){
                    foreach($created_at as $k=>$v)
                    {
                       $created_at[$k] = strtotime($v);
                    }  
                } 
             $where['o.create_time']=['between',$created_at];
            } 
       if(is_array($orderStatus)){
            $where['order_status'] = ['in',$orderStatus];
        }else{
            $where['order_status'] = $orderStatus;
        }   
        $orderList = Db::name("hotel_order")
        ->alias('o')
        ->where($where)
        ->join('__ORDER_REFUND__ orf','orf.order_sn=o.order_sn and refund_status=0','left')
        ->field('o.order_id,o.cancel_code,o.order_sn,o.linkman,refund_status,o.tel,o.start_time,o.order_price,o.create_time,o.order_status') 
        ->order('o.create_time', 'desc')
        ->select();
        if(count($orderList)>0){
            foreach ($orderList as $key => $value) {
                 $orderList[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
                 $orderList[$key]['start_time'] = date('Y-m-d',$value['start_time']);
                 $orderList[$key]['cancel_code'] = substr($value['cancel_code'],18 );

            } 
         if ($isCount){ 
            return count($orderList); 
          }
        } 
        return $orderList;

    }

      static function shopOrdersByPages($orderStatus, $isCount = false)
    { 
         $where = array(); 
         $get = Request::instance()->get();  
          $hotel_id = Session::get('hotel_id');
          $where = ['o.hotel_id'=>$hotel_id,'o.is_del'=>0];
            if (isset($get['order_sn']) && $get['order_sn'] != '' ){
                $where['o.order_sn'] = $get['order_sn'];
            } 
            if (isset($get['order_status']) && $get['order_status'] != ''){
                $where['order_status'] = $get['order_status'];
            }
            if (isset($get['cancel_code']) && $get['cancel_code'] != ''){
                $where['cancel_code'] = 'hotel_cancle_code_'.$get['cancel_code'];
            }   
           if (isset($get['selectdate']) && $get['selectdate'] != ''){
                $created_at=explode(' ~ ', $get['selectdate']); 
                if (isset($created_at) && is_array($created_at)){
                    foreach($created_at as $k=>$v)
                    {
                       $created_at[$k] = strtotime($v);
                    }  
                } 
             $where['o.create_time']=['between',$created_at];
            } 
       if(is_array($orderStatus)){
            $where['order_status'] = ['in',$orderStatus];
        }else{
            $where['order_status'] = $orderStatus;
        }   
        $orderList = Db::name("hotel_order")
        ->alias('o')
        ->where($where)
        ->join('__ORDER_REFUND__ orf','orf.order_sn=o.order_sn and refund_status=0','left')
        ->join('order_cancel oc','oc.order_sn=o.order_sn','left')
        ->join('hotel_admin ha','ha.h_admin_id=oc.cancel_id','left')
        ->field('o.order_id,o.cancel_code,o.order_sn,o.linkman,o.tel,o.start_time,o.order_price,o.create_time,o.order_status,oc.cancel_id,ha.admin_rename,oc.create_time as cancel_time') 
        ->order('cancel_time', 'desc')
        ->select();
        if(count($orderList)>0){
            foreach ($orderList as $key => $value) {
                $orderList[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
                 $orderList[$key]['start_time'] = date('Y-m-d H:i:s',$value['start_time']);
            } 
         if ($isCount){ 
            return count($orderList); 
          }
        } 
        return $orderList;

    }

    /**
     * [getOrderInfoById 根据酒店id获取酒店详情]
     * @Author   kendy
     * @DateTime 2019-12-23T11:08:42+0800
     * @return   [type]                   [description]
     */
     static function getOrderInfoById($where)
     {

           $resultData = Db::name('hotel_order')
            ->alias('ho')
            ->join('hotel h','ho.hotel_id=h.hotel_id','left')
            ->join('hotel_room hr','hr.room_id=ho.room_id','left')
            ->where($where)
            ->field('h.hotel_name,hr.room_name,h.hotel_tel,ho.order_id,ho.order_sn,ho.hotel_id,ho.room_id,ho.uid,ho.linkman,ho.tel,ho.start_time,
            ho.end_time,ho.living_days,ho.living_peason,ho.content,ho.order_status,ho.total_price,ho.coupon_id,
            ho.coupon_price,ho.order_price,ho.pay_type,ho.is_pay,ho.cancel_id,ho.is_appraise,ho.is_refund,ho.order_unique,ho.is_del,ho.create_time')
            ->find();
        if(empty($resultData)) return [];
        $nameObj = Db::name('hotel_orderlist')->where($where)->select();
        foreach ($nameObj as $k => $v) {
          $nameArr[] = $v['username'];
        }
       // $resultData['linkman'] = implode(' , ', $nameArr);
        $resultData['pay_type'] = lvPayType($resultData['pay_type']);
        $resultData['order_status'] = lvOrderStatus($resultData['order_status']);
        $resultData['create_time'] = date('Y-m-d H:i:s',$resultData['create_time']);
        $resultData['start_time'] = date('Y-m-d',$resultData['start_time']);
        $resultData['end_time'] = date('Y-m-d',$resultData['end_time']);
        $userInfo = new um;
        $resultData['username'] = $userInfo->getUserInfoById(['uid'=>$resultData['uid']])['nickname'];
        return $resultData;
     }

     /**
     * [cancelCode 核销订单]
     * @Author   kendy
     * @DateTime 2019-12-19T09:17:16+0800
     * @return   [type]                   [description]
     */
    static function cancelCode()
    {
        $post = Request::instance()->post();  
       /* $result = Db::name('hotel_order')
        ->where($where)
        ->find();
        if($result !== false){ */ 
        $order_sn = $post['order_sn'];
        //$eroom_id= $post['data']['eroom_id'];
        $where = ['order_sn'=>$order_sn,'ho.is_del'=>0,'order_status'=>1]; 
        $cancelId = Session::get('h_admin_id');
        $result = Db::name('hotel_order')
        ->alias("ho")
        ->field('order_id,ho.uid,ho.room_name,ho.order_sn,h.no_settled_order_fee,total_price,room_amount,ho.commission_rate,no_settled_order_num,order_price')
        ->join('hotel h','h.hotel_id=ho.hotel_id','left')
        ->where($where)
        ->find();   
        if($result !== false){
           Db::startTrans();
           try{
          $hotel_id = (int)Session::get('hotel_id');
         //计算订单佣金 
          $commissionFee = 0; 
          if($result['commission_rate']>0){
              $commissionFee = $result['total_price']*$result['room_amount']*$result['commission_rate']/1000;
           } 
 
        // 核销该订单信息 
            $OrderCancel = new ocm();
            $OrderCancel->orderCancel($cancelId,2,$result['order_id'],$order_sn,$result['order_price']);
         //创建订单日志 
            $logOrder = new lo();
            $logOrder->addLogOrder($result['order_id'],1, $cancelId, 3, '核销成功，用户已经入住'); 
           //给用户发送消息提示 1景点订单 2酒店订单 3旅行社订单
           //send_user_message(5, 2, $result['uid'],$result['order_sn'],$result['room_name'],$result['order_id'],2);
         //修改商家未计算订单数和未结算的订单佣金 
          Db::name("hotel")
         ->where("hotel_id",$hotel_id)
         ->setInc("no_settled_order_num",1);
          Db::name("hotel")
         ->where("hotel_id",$hotel_id)
         ->setDec("no_settled_order_fee",$commissionFee); 
         //修改订单的状态
         $upOrderStatus =  Db::name('hotel_order')
            ->alias("ho")
            ->where($where)
            ->update(['order_status'=>3,'commission_fee'=>$commissionFee]);   
            //修改房间的信息 
         Db::commit();
         return true;
       }catch(\Exection $e){
          Db::rollback();

          return false;
       }  
      }
        return false;
    }


   static function isAffirmOrder()
   { 
        $post = Request::instance()->post();
        $shopId = (int)Session::get('hotel_id');  
        $order_sn = (int)$post['order_sn'];
        $is_affirm = (int)$post['is_affirm']; 
        $cause =  empty($post['cause']) ? '' : (string)$post['cause'];  
        $hotelOrder = Db::name('hotel_order')
        ->alias('ho')
        ->join('user u','ho.uid = u.uid','left')
        ->join('hotel h','h.hotel_id=ho.hotel_id','left')
        ->field('order_id,h.latest_time,ho.tel,order_price,ho.uid,pay_type,ho.hotel_id,h.hotel_tel,room_name,ho.create_time,u.phone,order_sn')
        ->where(['order_sn'=>$order_sn,'ho.is_del'=>0,'order_status'=>6])
        ->find();   
        if(empty($hotelOrder)) return false; //无效的订单  
       //1为有空间 2为没有房间 
       if($is_affirm == 1)
       {
         $send = [
                '1'=>$hotelOrder['order_sn'],
                '2'=>$hotelOrder['room_name'],
                '3'=>$hotelOrder['latest_time'],
                '4'=>$hotelOrder['hotel_tel']

            ];
         $data['order_status'] = 1;
         Db::name('hotel_order')
         ->where('order_sn',$order_sn)
         ->update($data);
         //给用户发送短信通知，修改订单的状态  
         //
         sendJsmsMessage($hotelOrder['tel'],174981,$send);
         return true;
       }else{ 

         $send = [
                '1'=>$hotelOrder['order_sn'],
                '2'=> $cause
            ];  
         $data['order_status'] = 5;
         $data['cancel_id'] = 2;  
          $orf = new orf();
            $obj['order_sn'] = $hotelOrder['order_sn'];
            $obj['object_id'] = $hotelOrder['hotel_id']; 
            $obj['object_type'] = 4; 
            $obj['user_id'] = $hotelOrder['uid'];
            $obj['refund_status'] = 1;
            $obj['refund_reason'] = "酒店商户无房间退款";
            $obj['order_price'] = $hotelOrder['order_price'];   
         //退款 
         //查看支付类型
       $hotelOrder['refund_reason'] = "酒店商户".$cause."退款";
        $payType = $hotelOrder['pay_type'];//1支付宝 2微信   
         if($payType == 1){
            $rs = $orf->aliRefund($hotelOrder);
        }
        if($payType == 2){  
            $rs = $orf->weixinRefund($hotelOrder);
        } 
           
        if($rs == 'SUCCESS'){ 
            Db::name('hotel')
            ->where('hotel_id',$hotelOrder['hotel_id'])
            ->setDec('sum_sale',1);  
            Db::name('hotel_order')
            ->where('order_id',$hotelOrder['order_id'])
            ->update($data); 
            $orderRefund = new ore(); 
            $orderRefund->addOrderRefund($obj);     
        }else{ 
            return false; 
         }          

         //给用户发送短信
          sendJsmsMessage($hotelOrder['tel'],174982,$send);
       
         return true;
       } 
        return false;
   }

        static function getRoomInfoById($where){
        //获取没有入住的房间信息
          $resultData = Db::name('hotel_order')
          ->alias('ho')
          ->field('ho.room_name,ho.room_id,ho.hotel_id,ho.content')
          ->where($where)
          ->find();
          //获取该房间类型的房间号
          $resultData['roomList'] = Db::name('hotel_eroom')
          ->where('room_id',$resultData['room_id'])
          ->where('is_del',0)
          ->where('is_ruzhu',0)
          ->select();
          return $resultData; 
     }

}